package emailbeans;

import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import dto.EmployeeDTO;

@ManagedBean(name = "employeeEmailBean")
@SessionScoped
public class EmployeeEmailBean {
	
	@ManagedProperty(value = "#{employee}")
	EmployeeDTO employee;
	
	@SuppressWarnings("unused")
	private String message = null;
	private String subject = "MSG Systems New Account";
	private String smtpServ;
	@SuppressWarnings("unused")
	private String email="";	
	private String from;

	/**
	 * The constructor where is setting the proxy.
	 */
	public EmployeeEmailBean(){
		smtpServ = "msgc4i.msg.de";
	}
	
	
	/**
	 * Getter for address of sender.
	 * @return
	 */
	public String getFrom() {
		return from;
	}

/**
 * Setter for address of sender.
 * @param from
 */
	public void setFrom(String from) {
		this.from = from;
	}


	/**
	 * Getter for EmployeeDTO Employee.
	 * @return
	 */
	public EmployeeDTO getEmployee() {
		return employee;
	}

/**
 * Setter of EmployeeDTO Employee.
 * @param employee
 */
	public void setEmployee(EmployeeDTO employee) {
		this.employee = employee;
	}


	/**
	 * Getter for Message.
	 * This method build the message in a pretty format.
	 * @return message
	 */
	public String getMessage() {
		
		return " Hello "
		+this.getEmployee().getName() + " !\n"
		+ "Welcome to MSG Account! An new account of " + this.function(employee)
		+ " was created for you with the follow email address:\n "
		+ this.getEmployee().getEmail() + "\n\n"
		+ "For your authentication use follow information: \n\n"
		+"Username: "+this.getEmployee().getUsername()+ "\n"
		+"Password: "+this.getEmployee().getPassword()+"\n\n"
		+"For inconvenience, please contact on email: msg.info-office-cluj@msg-systems.com in order to fixed. \n"
		+"Thank You! \n\n"
		+"MSG SYSTEMS ROMANIA";
	}

/**
 * Setter for Message.
 * @param message
 */
	public void setMessage(String message) {
		this.message = message;
	}

/**
 * Getter for subject of message.
 * @return subject
 */
	public String getSubject() {
		return subject;
	}

/**
 * Setter for subject of message.
 * @param subject
 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

/**
 * Getter for proxy.
 * @return
 */
	public String getSmtpServ() {
		return smtpServ;
	}

/**
 * Setter for proxy.
 * @param smtpServ
 */
	public void setSmtpServ(String smtpServ) {
		this.smtpServ = smtpServ;
	}

/**
 * Getter for email address.
 * @return
 */
	public String getEmail() {
		return employee.getEmail();
	}

/**
 * Setter for email address.
 * @param email
 */
	public void setEmail(String email) {
		this.email = email;
	}


	/**
	 * This method return a String with function of employee by his rank
	 * @param em
	 * @return
	 */
	public String function(EmployeeDTO em){
		if(em.getRank()==1)
			return "Administrator";
		else if (em.getRank() == 2)
			return "Tester";
		else return null;
		
	}
	/**
	 * This method Authenticate the user to Msg Account, build the message and sent it to specified address.
	 * @return
	 */
	public void sendEmail() {
	
		
		try {
			Properties props = System.getProperties();

			// -- Attaching to default Session, or we could start a new one --
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.starttls.enable", "true");
			props.put("mail.smtp.host", smtpServ);
			props.put("mail.smtp.auth", "true");

			Authenticator auth = new SMTPAuthenticator();

			Session session = Session.getInstance(props, auth);

			// -- Create a new message --
			Message msg = new MimeMessage(session);
			// -- Set the FROM and TO fields --
			// System.out.println(employeeBean.getEmail());
			msg.setFrom(new InternetAddress(from, "MSG Systems"));

			msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(
					getEmail(), false));

			msg.setSubject(subject);

			// -- Set some other header information --
			msg.setHeader("MyMail", "Mr. XYZ");
			msg.setSentDate(new Date());

			// create the message part
			MimeBodyPart messageBodyPart = new MimeBodyPart();
			// String fileAttachment = "Z:/Projects/Orders/PrimewJSP.7z";
			// fill message

			messageBodyPart.setText(getMessage());

			Multipart multipart = new MimeMultipart();
			multipart.addBodyPart(messageBodyPart);

			// Put parts in message
			msg.setContent(multipart);

			// -- Send the message --
			Transport.send(msg);

			if(employee.getRank()== 1){
			try {
				FacesContext.getCurrentInstance().getExternalContext().redirect("/MSGCandidateTesting/faces/editAdmin.xhtml");
			} catch (IOException e) {
				e.printStackTrace();
			}}
			else if(employee.getRank() == 2){
				
				try {
					FacesContext.getCurrentInstance().getExternalContext().redirect("/MSGCandidateTesting/faces/alocateTesterUser.xhtml");
				} catch (IOException e) {
					e.printStackTrace();
				}	
				
			}
		
			
		
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println("Exception " + ex);
	
		}
	}
	
	/**
	 * Method that redirect to previous page
	 */
		public void backFromSend() {
			//set buttons
			//redirect to testerhome
			if(employee.getRank()== 1){
				try {
					FacesContext.getCurrentInstance().getExternalContext().redirect("/MSGCandidateTesting/faces/editAdmin.xhtml");
				} catch (IOException e) {
					e.printStackTrace();
				}}
				else if(employee.getRank() == 2){
					
					try {
						FacesContext.getCurrentInstance().getExternalContext().redirect("/MSGCandidateTesting/faces/alocateTesterUser.xhtml");
					} catch (IOException e) {
						e.printStackTrace();
					}	
					
				}

		}
		
	/**
	 * Inner Class that make the authentication on mail account.
	 * @author vornicub
	 *
	 */
	// Also include an inner class that is used for authentication purposes
	private class SMTPAuthenticator extends javax.mail.Authenticator {

		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			String username = "vornicub"; // specify your email id here
			// (sender's email id)
			String password = "vornicub"; // specify your password here
			return new PasswordAuthentication(username, password);
		}
	}
	
}
